package frame;

import mapper.GoodsMapper;
import org.apache.ibatis.session.SqlSession;
import pojo.Goods;
import utils.MybatisUtil;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.awt.Font;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.awt.Color;
import javax.swing.SwingConstants;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionEvent;

import javax.swing.*;
import java.awt.*;

public class OutputFrame extends MainFrame {
    private JPanel contentPane;
    private JTable table;
    private JTextField idField;
    private JTextField nameField;
    private JTextField shelfField;
    private JTextField numberField;
    private JTextField priceField;

    private List<Goods> goodsList = new ArrayList<>();
    private SqlSession sqlSession = MybatisUtil.getSession();
    // 创建userDao接口，然后通过反射来获取代理对象
    private GoodsMapper goodsMapper = sqlSession.getMapper(GoodsMapper.class);

    private boolean check(String str) {
        return str == null || str.equals("");
    }


    public OutputFrame() {
        setLocationRelativeTo(null);
        getContentPane().setLayout(null);

        JLabel lblNewLabel = new JLabel("仓库信息");
        lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
        lblNewLabel.setForeground(Color.BLUE);
        lblNewLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        lblNewLabel.setBounds(269, 14, 215, 33);
        getContentPane().add(lblNewLabel);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(215, 61, 518, 190);
        getContentPane().add(scrollPane);
        try {
            goodsList=goodsMapper.findAllGoods();
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        // 表头（列名）
        Object[] columnNames = {"货物编号", "货物名称", "货架号", "货物数量", "货物单价"};

        /*final Vector vector = new Vector();
        vector.add("货物编号");
        vector.add("货物名称");
        vector.add("货架号");
        vector.add("货物数量");
        vector.add("货物单价");*/
        Object[][] vectorRow = new Object[goodsList.size()][5];

        for (int i = 0 ; i < goodsList.size() ; i++){
            // 从列表中获取实体类
            for(int j = 0;j<5;j++){
                if(j==0)
                    vectorRow[i][j]=goodsList.get(i).getGid();
                if(j==1)
                    vectorRow[i][j]=goodsList.get(i).getgName();
                if(j==2)
                    vectorRow[i][j]=goodsList.get(i).getgShelf();
                if(j==3)
                    vectorRow[i][j]=goodsList.get(i).getgCnt();
                if(j==4)
                    vectorRow[i][j]=goodsList.get(i).getgPrice();
            }
        }

        table = new JTable(vectorRow,columnNames);
        scrollPane.setViewportView(table);

        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                // 获取货物编号
                String gid = (String) table.getValueAt(table.getSelectedRow(), 0).toString();
                //获取货物名称
                String gname = (String)table.getValueAt(table.getSelectedRow(), 1);
                //获取货架号
                String gshelf =(String)table.getValueAt(table.getSelectedRow(), 2);
                //获取货物数量
                String gcnt=(String)table.getValueAt(table.getSelectedRow(), 3).toString();
                //获取货物单价
                String gprice=(String)table.getValueAt(table.getSelectedRow(), 4).toString();
                //将数据设置进文本框
                idField.setText(gid);
                nameField.setText(gname);
                shelfField.setText(gshelf);
                numberField.setText(gcnt);
                priceField.setText(gprice);
                super.mouseClicked(e);
            }
        });

        JLabel lblNewLabel_1 = new JLabel("货物编号：");
        lblNewLabel_1.setFont(new Font("微软雅黑", Font.BOLD, 14));
        lblNewLabel_1.setBounds(215, 274, 82, 33);
        getContentPane().add(lblNewLabel_1);

        JLabel lblNewLabel_1_1 = new JLabel("货物名称：");
        lblNewLabel_1_1.setFont(new Font("微软雅黑", Font.BOLD, 14));
        lblNewLabel_1_1.setBounds(215, 308, 82, 33);
        getContentPane().add(lblNewLabel_1_1);

        JLabel lblNewLabel_1_2 = new JLabel("货架号：");
        lblNewLabel_1_2.setFont(new Font("微软雅黑", Font.BOLD, 14));
        lblNewLabel_1_2.setBounds(215, 346, 82, 33);
        getContentPane().add(lblNewLabel_1_2);

        JLabel lblNewLabel_1_3 = new JLabel("货物数量：");
        lblNewLabel_1_3.setFont(new Font("微软雅黑", Font.BOLD, 14));
        lblNewLabel_1_3.setBounds(215, 380, 82, 33);
        getContentPane().add(lblNewLabel_1_3);

        JLabel lblNewLabel_1_4 = new JLabel("货物单价：");
        lblNewLabel_1_4.setFont(new Font("微软雅黑", Font.BOLD, 14));
        lblNewLabel_1_4.setBounds(215, 414, 82, 33);
        getContentPane().add(lblNewLabel_1_4);

        idField = new JTextField();
        idField.setBounds(288, 281, 177, 26);
        getContentPane().add(idField);
        idField.setColumns(10);

        nameField = new JTextField();
        nameField.setColumns(10);
        nameField.setBounds(288, 315, 177, 26);
        getContentPane().add(nameField);

        shelfField = new JTextField();
        shelfField.setColumns(10);
        shelfField.setBounds(288, 351, 177, 26);
        getContentPane().add(shelfField);

        numberField = new JTextField();
        numberField.setColumns(10);
        numberField.setBounds(288, 385, 177, 26);
        getContentPane().add(numberField);

        priceField = new JTextField();
        priceField.setColumns(10);
        priceField.setBounds(288, 419, 177, 26);
        getContentPane().add(priceField);

        JButton btnNewButton = new JButton("出库");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 查询某个商品的信息
                Goods nowG = goodsMapper.findGoodById(Integer.parseInt(idField.getText()));
                String inputNum = numberField.getText();
                //输入不能为非负整数
                String reg3 = "^\\d+$";
                if (!inputNum.matches(reg3)) {
                    JOptionPane.showMessageDialog(null, "出库数量必须为非负整数！");
                    return;
                }
                int num1 = Integer.parseInt(numberField.getText());
                int num2 = nowG.getgCnt();
                if (num1 > num2) {
                    JOptionPane.showMessageDialog(null, "输入数量不能超过原有货物的数量！");
                } else if (num1 < num2) {
                    int cnt = goodsMapper.updateGoodsById(Integer.parseInt(idField.getText()), num1);
                    if (cnt > 0) {
                        sqlSession.commit();
                       // empLook.setGoodTotal(empLook.getGoodTotal() - num1);
                        JOptionPane.showMessageDialog(null, "出库成功！");
                        setVisible(false);
                        new OutputFrame().setVisible(true);
                    } else {
                        JOptionPane.showMessageDialog(null, "出库失败！");
                    }
                } else { //直接删除该商品
                    int cnt = goodsMapper.deleteGoodById(Integer.parseInt(idField.getText()));
                    if (cnt > 0) {
                        sqlSession.commit();
                        // 清空表单数据
                        idField.setText("");
                        nameField.setText("");
                        shelfField.setText("");
                        numberField.setText("");
                        priceField.setText("");
                        JOptionPane.showMessageDialog(null,"出库成功！");
                        setVisible(false);
                        new OutputFrame().setVisible(true);

                    } else {
                        JOptionPane.showMessageDialog(null,"出库失败！");
                    }
                }

                /*if(id == 0){
                    JOptionPane.showMessageDialog(null, "修改失败请选择需要修改的记录！");
                }else{
                    try {
                        //给出提示
                        //4个参数：1.null 2.提示内容 3.标题 4.按钮类型
                        int mess = JOptionPane.showConfirmDialog(
                                null,"确定修改记录？","友情提示：",
                                JOptionPane.YES_NO_OPTION );
                        //点击确定按钮之后的事件
                        //0 == 确定 ，1 == 取消
                        if(mess == 0){
                            //调用删除方法
                            Storage storage = new Storage();
                            storage.setStoragename(nameField.getText());
                            storage.setStoragestyle(styleField.getText());
                            storage.setStorageID(Integer.parseInt(idField.getText()));
                            s.Update(storage,"update storage set storagename = ?,storagestyle=?,storageID=? where id = "+ id);
                            //提示删除成功
                            JOptionPane.showMessageDialog(null, "修改成功");
                            setVisible(false);
                            new HomeUpdate(user).setVisible(true);


                        }
                    }catch (Exception e2) {
                        // TODO: handle exception
                    }
                }*/
            }
        });
        btnNewButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        btnNewButton.setBounds(215, 468, 112, 34);
        getContentPane().add(btnNewButton);

        JButton btnNewButton_1 = new JButton("删除");
        btnNewButton_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 直接通过编号删除书籍信息、
                int cnt = goodsMapper.deleteGoodById(Integer.parseInt(idField.getText()));
                if (cnt > 0) {
                    sqlSession.commit();
                    // 清空表单数据
                    idField.setText("");
                    nameField.setText("");
                    shelfField.setText("");
                    numberField.setText("");
                    priceField.setText("");

                    JOptionPane.showMessageDialog(null, "删除商品成功！");
                    setVisible(false);
                    new OutputFrame().setVisible(true);
                    // 清空表单
                } else {
                    JOptionPane.showMessageDialog(null, "删除商品失败！");
                }
            }
        });
        btnNewButton_1.setFont(new Font("微软雅黑", Font.BOLD, 14));
        btnNewButton_1.setBounds(436, 468, 112, 34);
        getContentPane().add(btnNewButton_1);
    }
}
